# -*- coding:utf-8 -*-
import requests
import json
import base64
import time
import math
import hashlib
import os,pathlib
from tqdm import tqdm

URL = "http://117.132.181.235:9050"  # 推理网关的地址
# URL = "http://172.31.184.162:30800"  # 推理网关的地址
# URL = "http://127.0.0.1:8000"
TDEV = 0  # 测试机器与北京时间的偏差（慢多少毫秒）

Path = "/ebikepredict"  # 对应“API管理”中的“PATH映射”
APPID = "firedemo"  # 对应“授权管理”中的“应用标识”
APPKey = "afb5088f8aca764a00ea8e3cba50f8e3"  # 对应“授权管理”中的“应用秘钥”


# 适配推理网关协议的头部构造方法
def create_header():
    appid = APPID
    appKey = APPKey
    uuid = "52a7bb1fc08841ad9efc76d8ae1ef07b"
    appName = Path.split('/')[1]
    for i in range(24 - len(appName)):
        appName += "0"
    capabilityname = appName
    # print(len(capabilityname))
    csid = appid + capabilityname + uuid
    tmp_xServerParam = {
        "appid": appid,
        "csid": csid
    }
    # print(tmp_xServerParam)
    xCurTime = str(int(math.floor(time.time())) + TDEV)
    # print(xCurTime)
    xServerParam = str(base64.b64encode(json.dumps(
        tmp_xServerParam).encode('utf-8')), encoding="utf8")
    # xServerParam = str(base64.b64encode(json.dumps(tmp_xServerParam).encode('utf-8')))

    # turn to bytes
    xCheckSum = hashlib.md5(
        bytes(appKey + xCurTime + xServerParam, encoding="utf8")).hexdigest()
    # xCheckSum = hashlib.md5(bytes(appKey + xCurTime + xServerParam)).hexdigest()

    header = {
        # "appKey": appKey,
        "X-Server-Param": xServerParam,
        "X-CurTime": xCurTime,
        "X-CheckSum": xCheckSum,
        "Content-Type": "application/json"
    }

    return header


files = {'file': open('test.jpg','rb')}
#r = requests.post(url, files=files)

print(URL + Path)
res = requests.post(url=URL + Path, headers=create_header(),files=files,verify=False)
print("返回状态码：\t" + str(res.status_code))
print("返回头部: \t", res.headers)
print(res.text.encode('utf-8').decode('unicode_escape'))
